<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card class="stat-card total-submissions">
          <div class="stat-content">
            <div class="stat-icon">
              <i class="el-icon-cpu"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.totalSubmissions }}</div>
              <div class="stat-label">总提交数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card passed-count">
          <div class="stat-content">
            <div class="stat-icon">
              <i class="el-icon-check"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.passedCount }}</div>
              <div class="stat-label">通过数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card failed-count">
          <div class="stat-content">
            <div class="stat-icon">
              <i class="el-icon-close"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.failedCount }}</div>
              <div class="stat-label">失败数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card average-score">
          <div class="stat-content">
            <div class="stat-icon">
              <i class="el-icon-time"></i>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ statistics.averageScore }}</div>
              <div class="stat-label">平均分</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="学生ID" prop="userId">
          <el-input
            v-model="queryParams.userId"
            placeholder="请输入学生ID"
            clearable
            size="small"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="OJ题目ID" prop="problemId">
          <el-input
            v-model="queryParams.problemId"
            placeholder="请输入OJ题目ID"
            clearable
            size="small"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="编程语言" prop="language">
          <el-select
            v-model="queryParams.language"
            placeholder="请选择编程语言"
            clearable
            size="small"
            style="width: 200px"
          >
            <el-option label="C++" value="cpp" />
            <el-option label="Java" value="java" />
            <el-option label="Python" value="python" />
            <el-option label="C" value="c" />
            <el-option label="JavaScript" value="js" />
          </el-select>
        </el-form-item>
        <el-form-item label="执行状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择执行状态"
            clearable
            size="small"
            style="width: 200px"
          >
            <el-option label="评测中" value="评测中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="编译错误" value="编译错误" />
            <el-option label="运行时错误" value="运行时错误" />
            <el-option label="时间超限" value="时间超限" />
            <el-option label="内存超限" value="内存超限" />
          </el-select>
        </el-form-item>
        <el-form-item label="编译状态" prop="compileStatus">
          <el-select
            v-model="queryParams.compileStatus"
            placeholder="请选择编译状态"
            clearable
            size="small"
            style="width: 200px"
          >
            <el-option label="成功" value="成功" />
            <el-option label="失败" value="失败" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:oj:submissions:add']"
          >+ 新增提交</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:oj:submissions:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:oj:submissions:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:oj:submissions:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-refresh"
            size="mini"
            :disabled="multiple"
            @click="handleRejudge"
            v-hasPermi="['system:oj:submissions:edit']"
          >重新评测</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="submissionList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="提交ID" align="center" prop="submissionId" width="120" />
        <el-table-column label="学生ID" align="center" prop="userId" width="120" />
        <el-table-column label="OJ题目ID" align="center" prop="problemId" width="120" />
        <el-table-column label="开课ID" align="center" prop="courseId" width="120" />
        <el-table-column label="编程语言" align="center" prop="language" width="100">
          <template slot-scope="scope">
            <el-tag :type="getLanguageTagType(scope.row.language)">
              {{ getLanguageName(scope.row.language) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件名" align="center" prop="fileName" width="150" />
        <el-table-column label="提交时间" align="center" prop="submissionTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.submissionTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="编译状态" align="center" prop="compileStatus" width="100">
          <template slot-scope="scope">
            <el-tag :type="getCompileStatusType(scope.row.compileStatus)">
              {{ scope.row.compileStatus || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行状态" align="center" prop="status" width="120">
          <template slot-scope="scope">
            <el-tag :type="getExecutionStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最终得分" align="center" prop="score" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.score" class="score-text">{{ scope.row.score }}</span>
            <span v-else class="no-score">--</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['system:oj:submissions:query']"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:oj:submissions:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:oj:submissions:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh"
              @click="handleRejudge(scope.row)"
              v-hasPermi="['system:oj:submissions:edit']"
            >重测</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学生ID" prop="userId">
              <el-input v-model="form.userId" placeholder="请输入学生ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="OJ题目ID" prop="problemId">
              <el-input v-model="form.problemId" placeholder="请输入OJ题目ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="编程语言" prop="language">
              <el-select v-model="form.language" placeholder="请选择编程语言" style="width: 100%">
                <el-option label="C++" value="cpp" />
                <el-option label="Java" value="java" />
                <el-option label="Python" value="python" />
                <el-option label="C" value="c" />
                <el-option label="JavaScript" value="js" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交类型" prop="submissionType">
              <el-select v-model="form.submissionType" placeholder="请选择提交类型" style="width: 100%">
                <el-option label="练习" value="practice" />
                <el-option label="竞赛" value="contest" />
                <el-option label="作业" value="homework" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="代码内容" prop="code">
          <el-input
            v-model="form.code"
            type="textarea"
            :rows="15"
            placeholder="请输入代码内容"
            show-word-limit
            maxlength="10000"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否开启O2优化">
              <el-switch v-model="form.enableO2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog title="提交详情" :visible.sync="viewOpen" width="900px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="提交ID">{{ viewForm.submissionId }}</el-descriptions-item>
        <el-descriptions-item label="学生ID">{{ viewForm.userId }}</el-descriptions-item>
        <el-descriptions-item label="OJ题目ID">{{ viewForm.problemId }}</el-descriptions-item>
        <el-descriptions-item label="编程语言">{{ getLanguageName(viewForm.language) }}</el-descriptions-item>
        <el-descriptions-item label="提交状态">{{ viewForm.status }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ parseTime(viewForm.submissionTime) }}</el-descriptions-item>
        <el-descriptions-item label="执行时间">{{ viewForm.executionTime }}ms</el-descriptions-item>
        <el-descriptions-item label="内存使用">{{ viewForm.memoryUsage }}MB</el-descriptions-item>
        <el-descriptions-item label="测试用例通过">{{ viewForm.testCasesPassed }}/{{ viewForm.totalTestCases }}</el-descriptions-item>
        <el-descriptions-item label="最终得分">{{ viewForm.score || '--' }}</el-descriptions-item>
      </el-descriptions>
      
      <el-divider content-position="left">代码内容</el-divider>
      <el-input
        v-model="viewForm.code"
        type="textarea"
        :rows="15"
        readonly
        show-word-limit
      />
      
      <div v-if="viewForm.compileError" style="margin-top: 20px;">
        <el-divider content-position="left">编译错误</el-divider>
        <el-alert
          :title="viewForm.compileError"
          type="error"
          :closable="false"
          show-icon
        />
      </div>
      
      <div v-if="viewForm.runtimeError" style="margin-top: 20px;">
        <el-divider content-position="left">运行时错误</el-divider>
        <el-alert
          :title="viewForm.runtimeError"
          type="warning"
          :closable="false"
          show-icon
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubmission, getSubmission, delSubmission, addSubmission, updateSubmission, rejudgeSubmission } from "@/api/system/oj-practice";

export default {
  name: "OjSubmissions",
  components: {
    Pagination: () => import("@/components/Pagination")
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 提交记录表格数据
      submissionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹出层
      viewOpen: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        problemId: null,
        language: null,
        status: null,
        compileStatus: null
      },
      // 表单参数
      form: {},
      // 查看表单参数
      viewForm: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "学生ID不能为空", trigger: "blur" }
        ],
        problemId: [
          { required: true, message: "OJ题目ID不能为空", trigger: "blur" }
        ],
        language: [
          { required: true, message: "编程语言不能为空", trigger: "change" }
        ],
        code: [
          { required: true, message: "代码内容不能为空", trigger: "blur" }
        ]
      },
      // 统计数据
      statistics: {
        totalSubmissions: 156,
        passedCount: 89,
        failedCount: 67,
        averageScore: 78.5
      }
    };
  },
  created() {
    this.getList();
    this.getStatistics();
  },
  methods: {
    /** 查询提交记录列表 */
    getList() {
      this.loading = true;
      listSubmission(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.submissionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取统计数据 */
    getStatistics() {
      // 这里应该调用后端接口获取真实统计数据
      // 暂时使用模拟数据
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        submissionId: null,
        userId: null,
        problemId: null,
        code: null,
        language: null,
        submissionType: "practice",
        enableO2: false,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.submissionId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加代码提交";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const submissionId = row.submissionId || this.ids[0];
      getSubmission(submissionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改代码提交";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewForm = { ...row };
      this.viewOpen = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.submissionId != null) {
            updateSubmission(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubmission(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const submissionIds = row.submissionId || this.ids;
      this.$modal.confirm('是否确认删除提交记录编号为"' + submissionIds + '"的数据项？').then(function() {
        return delSubmission(submissionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 重新评测按钮操作 */
    handleRejudge(row) {
      const submissionId = row.submissionId || this.ids[0];
      this.$modal.confirm('是否确认重新评测提交记录编号为"' + submissionId + '"的数据项？').then(function() {
        return rejudgeSubmission(submissionId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("重新评测成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/oj/submission/export', {
        ...this.queryParams
      }, `oj_submission_${new Date().getTime()}.xlsx`);
    },
    // 添加日期范围处理
    addDateRange(params, dateRange) {
      const search = params;
      search.params = typeof (search.params) === 'object' && search.params !== null ? search.params : {};
      if (null != dateRange && '' != dateRange) {
        search.params["beginTime"] = dateRange[0];
        search.params["endTime"] = dateRange[1];
      }
      return search;
    },
    // 表单重置工具方法
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
      }
    },
    // 时间格式化工具方法
    parseTime(time, cFormat) {
      if (arguments.length === 0 || !time) {
        return null;
      }
      const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
      let date;
      if (typeof time === 'object') {
        date = time;
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time);
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        return value.toString().padStart(2, '0');
      });
      return time_str;
    },
    // 获取编程语言标签类型
    getLanguageTagType(language) {
      const typeMap = {
        'cpp': 'primary',
        'java': 'success',
        'python': 'warning',
        'c': 'info',
        'js': 'danger'
      };
      return typeMap[language] || 'info';
    },
    // 获取编程语言名称
    getLanguageName(language) {
      const nameMap = {
        'cpp': 'C++',
        'java': 'Java',
        'python': 'Python',
        'c': 'C',
        'js': 'JavaScript'
      };
      return nameMap[language] || language;
    },
    // 获取编译状态标签类型
    getCompileStatusType(status) {
      return status === '成功' ? 'success' : 'danger';
    },
    // 获取执行状态标签类型
    getExecutionStatusType(status) {
      const typeMap = {
        '已完成': 'success',
        '评测中': 'warning',
        '编译错误': 'danger',
        '运行时错误': 'danger',
        '时间超限': 'warning',
        '内存超限': 'warning'
      };
      return typeMap[status] || 'info';
    }
  }
};
</script>

<style scoped>
.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  font-size: 48px;
  margin-right: 20px;
  opacity: 0.8;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.total-submissions .stat-icon {
  color: #409EFF;
}

.passed-count .stat-icon {
  color: #67C23A;
}

.failed-count .stat-icon {
  color: #E6A23C;
}

.average-score .stat-icon {
  color: #909399;
}

.search-card {
  margin-bottom: 20px;
}

.action-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.score-text {
  font-weight: bold;
  color: #67C23A;
}

.no-score {
  color: #909399;
}

.mb8 {
  margin-bottom: 8px;
}

.el-divider {
  margin: 20px 0;
}
</style> 